<script lang="ts">
import { getPostDetail } from '@/api/community'
import { userInfoGetService } from '@/api/user'
import { ElMessage } from 'element-plus'
import { Clock, ArrowLeft, Pointer, Star, Delete } from '@element-plus/icons-vue'
import { useTokenStore } from '@/stores/token'

export default {
    components: {
        Clock,
        ArrowLeft,
        Pointer,
        Star,
        Delete
    },
    data() {
        // 定义默认的假评论数据，与帖子字段保持一致
        const defaultComments = [
            {
                id: '1',
                title: '技术社区交流心得',
                content: '文章结构清晰，观点鲜明。特别是关于技术选型的分析很有见地。期待更多类似的分享！',
                postType: 'community',
                createTime: '2024/12/15 14:20',
                likeCount: 5,
                viewCount: 7,
                username: '技术探索者',
                avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
                isLiked: false,
                isViewed: false,
                postId: ''
            },
            {
                id: '3',
                title: '项目评估与反馈',
                content: '从架构设计的角度来看，这个方案的扩展性和维护性都很好。建议可以再补充一下高并发场景下的处理方案。',
                postType: 'task',
                createTime: '2024/01/07 16:45',
                likeCount: 7,
                viewCount: 4,
                username: '架构师小李',
                avatar: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
                isLiked: false,
                isViewed: false,
                postId: ''
            }
        ];

        return {
            post: {
                id: '',
                title: '',
                content: '',
                postType: '',
                createTime: '',
                likeCount: 0,
                viewCount: 0,
                username: ''
            },
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            commentContent: '',
            comments: defaultComments,
            currentUser: null,
        }
    },
    methods: {
        getTagType(postType) {
            const types = {
                'programmer': 'success',
                'task': 'warning',
                'community': 'info'
            }
            return types[postType] || 'info'
        },
        async getPostDetail() {
            try {
                const postId = this.$route.params.id;
                const response = await getPostDetail(postId);
                if (response && response.data) {
                    this.post = response.data;
                    // 获取存储的评论，如果没有则使用默认评论
                    const storedComments = this.getStoredComments();
                    if (storedComments && storedComments.length > 0) {
                        this.comments = storedComments;
                    } else {
                        // 如果没有存储的评论，将默认评论的 postId 设置为当前帖子 ID
                        this.comments.forEach(comment => {
                            comment.postId = postId;
                        });
                        // 保存到 localStorage
                        this.saveCommentsToStorage();
                    }
                }
            } catch (error) {
                console.error('获取帖子详情失败:', error);
                ElMessage.error('获取帖子详情失败');
            }
        },
        goBack() {
            this.$router.go(-1);
        },
        handlecomment() {

        },
        handleLike(postId) {
            const post = this.posts.find(post => post.id === postId);
            if (post) {
                // 获取已存储的点赞数据
                const likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};

                // 检查是否已经点赞过
                if (likedPosts[postId] && likedPosts[postId].hasLiked) {
                    ElMessage.warning('您已经点赞过这篇帖子了');
                    return;
                }

                // 更新点赞数
                post.likeCount += 1;

                // 更新存储数据
                likedPosts[postId] = {
                    likeCount: post.likeCount,
                    viewCount: post.viewCount,
                    hasLiked: true // 标记该帖子已被点赞
                };

                // 保存到 localStorage
                localStorage.setItem('likedPosts', JSON.stringify(likedPosts));

                console.log(`帖子 ${postId} 被点赞了! 当前点赞数: ${post.likeCount}`);
                ElMessage.success('点赞成功！');

                // 如果当前是最热帖子页面，重新排序
                if (this.activeName === 'second') {
                    this.posts.sort((a, b) => b.likeCount - a.likeCount);
                }
            } else {
                console.log(`没有找到 ID 为 ${postId} 的帖子`);
                ElMessage.error('点赞失败，帖子不存在');
            }
        },
        handlefavorite(postId) {
            const post = this.posts.find(post => post.id === postId);
            if (post) {
                // 获取已存储的收藏数据
                const favoritePosts = JSON.parse(localStorage.getItem('favoritePosts')) || {};

                // 检查是否已经收藏过
                if (favoritePosts[postId] && favoritePosts[postId].hasFavorited) {
                    ElMessage.warning('您已经收藏过这篇帖子了');
                    return;
                }

                // 更新收藏数
                post.viewCount = (post.viewCount || 0) + 1;

                // 更新存储数据
                favoritePosts[postId] = {
                    viewCount: post.viewCount,
                    hasFavorited: true
                };

                // 保存到 localStorage
                localStorage.setItem('favoritePosts', JSON.stringify(favoritePosts));

                ElMessage.success('收藏成功！');
            } else {
                ElMessage.error('收藏失败，帖子不存在');
            }
        },
        async submitComment() {
            if (!this.commentContent.trim()) {
                ElMessage.warning('请输入评论内容');
                return;
            }

            const tokenStore = useTokenStore();
            if (!tokenStore.token) {
                ElMessage.warning('请先登录后再评论');
                return;
            }

            try {
                // 使用已有的获取用户信息方法
                const response = await userInfoGetService();
                const userInfo = response.data;

                const postId = this.$route.params.id;
                const newComment = {
                    id: Date.now().toString(),
                    title: this.post.title,
                    content: this.commentContent,
                    postType: this.post.postType,
                    createTime: new Date().toLocaleString(),
                    likeCount: 0,
                    viewCount: 0,
                    username: userInfo.nickname || userInfo.username || '匿名用户', // 优先使用昵称
                    avatar: userInfo.avatar || this.userAvatar,
                    isLiked: false,
                    isViewed: false,
                    postId: postId
                };

                this.comments.unshift(newComment);
                this.commentContent = '';
                this.saveCommentsToStorage();
                ElMessage.success('评论发布成功！');
            } catch (error) {
                console.error('发表评论失败:', error);
                ElMessage.error('发表评论失败');
            }
        },
        likeComment(comment) {
            if (comment.isLiked) {
                comment.likeCount--;
            } else {
                comment.likeCount++;
            }
            comment.isLiked = !comment.isLiked;
            this.saveCommentsToStorage();
        },
        viewComment(comment) {
            if (comment.isViewed) {
                comment.viewCount--;
            } else {
                comment.viewCount++;
            }
            comment.isViewed = !comment.isViewed;
            this.saveCommentsToStorage();
        },

        getStoredComments() {
            try {
                const allComments = JSON.parse(localStorage.getItem('postComments')) || {};
                const postId = this.$route.params.id;
                return allComments[postId] || [];
            } catch (error) {
                console.error('获取存储的评论失败:', error);
                return [];
            }
        },
        saveCommentsToStorage() {
            try {
                const postId = this.$route.params.id;
                const allComments = JSON.parse(localStorage.getItem('postComments')) || {};
                allComments[postId] = this.comments;
                localStorage.setItem('postComments', JSON.stringify(allComments));
            } catch (error) {
                console.error('保存评论失败:', error);
                ElMessage.error('保存评论失败');
            }
        },
        async getCurrentUser() {
            try {
                const response = await userInfoGetService();
                this.currentUser = response.data;
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        },
        deleteComment(commentId) {
            const index = this.comments.findIndex(comment => comment.id === commentId);
            if (index !== -1) {
                this.comments.splice(index, 1);
                this.saveCommentsToStorage();
                ElMessage.success('评论删除成功');
            }
        },
        isCommentAuthor(comment) {
            return this.currentUser && 
                   (this.currentUser.nickname === comment.username || 
                    this.currentUser.username === comment.username);
        }
    },
    mounted() {
        this.getPostDetail();
        this.getCurrentUser();
    }
}
</script>


<template>
    <div class="page-container">
        <div class="rank-image">
            <img src="/src/assets/zphb.png" alt="排行榜">
        </div>

        <div class="post-detail">
            <el-card class="detail-card">
                <!-- 帖子头部 -->
                <div class="post-header">
                    <div class="user-info">
                        <el-avatar :src="userAvatar" :size="50" class="avatar" />
                        <div class="user-meta">
                            <div class="user-top">
                                <span class="username">{{ post.username }}</span>
                                <el-tag :type="getTagType(post.postType)" effect="light" class="post-type-tag">
                                    {{ post.postType }}
                                </el-tag>
                            </div>
                            <span class="post-time">
                                <el-icon>
                                    <Clock />
                                </el-icon>
                                {{ post.createTime }}
                            </span>
                        </div>
                    </div>
                </div>

                <!-- 帖子内容 -->
                <div class="post-content">
                    <h1 class="title">{{ post.title }}</h1>
                    <div class="content">{{ post.content }}</div>
                </div>

                <!-- 交互按钮 -->
                <div class="post-actions">
                    <div class="card-footer">
                        <div class="interaction-item" @click="handleLike(post.id)">
                            <img src="@/assets/like.png" alt="点赞">
                            <span>{{ post.likeCount }}</span>
                        </div>
                        <div class="interaction-item" @click="handlefavorite(post.id)">
                            <img src="@/assets/favorite.png" alt="收藏">
                            <span>{{ post.viewCount }}</span>
                        </div>
                        <div class="interaction-item" @click="handlecomment">
                            <img src="@/assets/comment.png" alt="评论">
                            <span>评论</span>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 返回按钮 -->
            <div class="back-section">
                <el-button @click="goBack" class="back-button" type="primary">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                    返回列表
                </el-button>
            </div>

            <!-- 新增：评论区域 -->
            <el-card class="comment-section">
                <template #header>
                    <div class="comment-header">
                        <h3>评论区</h3>
                        <span class="comment-count">{{ comments.length }}条评论</span>
                    </div>
                </template>

                <!-- 评论输入框 -->
                <div class="comment-input">
                    <el-avatar :src="userAvatar" :size="40" class="comment-avatar" />
                    <div class="input-wrapper">
                        <el-input v-model="commentContent" type="textarea" :rows="3" placeholder="写下你的评论..."
                            resize="none" />
                        <el-button type="primary" @click="submitComment" :disabled="!commentContent.trim()"
                            class="submit-btn">
                            发表评论
                        </el-button>
                    </div>
                </div>

                <!-- 评论列表 -->
                <div class="comment-list">
                    <div v-for="comment in comments" :key="comment.id" class="comment-item">
                        <el-avatar :src="comment.avatar" :size="40" class="comment-avatar" />
                        <div class="comment-content">
                            <div class="comment-header">
                                <div class="comment-user">
                                    <span class="comment-username">{{ comment.username }}</span>
                                    <el-popconfirm
                                        v-if="isCommentAuthor(comment)"
                                        title="确定要删除这条评论吗？"
                                        confirm-button-text="确定"
                                        cancel-button-text="取消"
                                        @confirm="deleteComment(comment.id)"
                                    >
                                        <template #reference>
                                            <el-button 
                                                type="danger" 
                                                size="small"
                                                link
                                            >
                                                <el-icon><Delete /></el-icon>
                                            </el-button>
                                        </template>
                                    </el-popconfirm>
                                </div>
                                <span class="comment-time">{{ comment.createTime }}</span>
                            </div>
                            <p class="comment-text">{{ comment.content }}</p>
                            <div class="comment-actions">
                                <span class="like-btn" :class="{ 'liked': comment.isLiked }"
                                    @click="likeComment(comment)">
                                    <img src="/src/assets/like.png" alt="喜欢">
                                    {{ comment.likeCount }}
                                </span>
                                <span class="view-btn" :class="{ 'viewed': comment.isViewed }"
                                    @click="viewComment(comment)">
                                    <img src="/src/assets/favorite.png" alt="收藏">
                                    {{ comment.viewCount }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 新增广告词区块 -->
        <div class="ad-container">
            <div class="ad-block">
                <h3>云上开发</h3>
                <p>专业的云开发服务</p>
                <p>快速部署，高效可靠</p>
            </div>
            <div class="ad-block">
                <h3>专业团队</h3>
                <p>资深工程师</p>
                <p>一对一服务</p>
            </div>
            <div class="ad-block">
                <h3>技术支持</h3>
                <p>7*24小时在线</p>
                <p>快速响应需求</p>
            </div>
        </div>
    </div>
    <el-footer>
        <div class="footer">
            <a href="#">动态公告</a> |
            <a href="#">帮助</a> |
            <a href="#">关于我们</a> |
            <a href="#">合作伙伴</a> |
            <a href="#">意见反馈</a> |
            <text style="color: rgb(78, 77, 77);">@"码上有钱"程序员接单平台</text>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>
</template>


<style scoped>
.page-container {
    display: flex;
    gap: 24px;
    max-width: 1200px;
    margin: 32px auto;
    padding: 0 16px;
    position: relative;
}

.rank-image {
    position: fixed;
    left: 24px;
    top: 350px;
    width: 150px;
}

.rank-image img {
    width: 200px;
    height: auto;
    transition: transform 0.3s ease;
}

.rank-image img:hover {
    transform: scale(1.05);
}

.post-detail {
    flex: 1;
    margin-left: 190px;
    max-width: 800px;
}

.detail-card {
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    padding: 24px;
}

.post-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.avatar {
    border: 2px solid #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.user-top {
    display: flex;
    align-items: center;
    gap: 12px;
}

.username {
    font-size: 16px;
    font-weight: 600;
    color: #333;
}

.post-type-tag {
    font-size: 12px;
    padding: 0 8px;
    height: 24px;
    line-height: 24px;
    border-radius: 4px;
}

.post-time {
    font-size: 13px;
    color: #8c8c8c;
    display: flex;
    align-items: center;
    gap: 4px;
}

.post-tag :deep(.el-tag) {
    font-size: 14px;
    padding: 6px 12px;
    border-radius: 6px;
}

.title {
    font-size: 24px;
    font-weight: 600;
    color: #2c3e50;
    margin: 24px 0;
    line-height: 1.4;
}

.content {
    font-size: 16px;
    line-height: 1.8;
    color: #4a4a4a;
    margin-bottom: 32px;
    white-space: pre-wrap;
    word-break: break-word;
    background: #f9fafb;
    padding: 24px;
    border-radius: 8px;
}

.post-actions {
    border-top: 1px solid #eee;
    padding-top: 20px;
    margin-top: 20px;
}

.card-footer {
    display: flex;
    justify-content: flex-end;
    gap: 20px;
    padding: 10px 0;
}

.interaction-item {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.interaction-item:hover {
    transform: translateY(-2px);
}

.interaction-item img {
    width: 20px;
    height: 20px;
}

.interaction-item span {
    color: #666;
    font-size: 14px;
}

.back-section {
    margin-top: 24px;
    display: flex;
    justify-content: center;
}

.back-button {
    padding: 12px 24px;
    font-size: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.back-button:hover {
    transform: translateX(-4px);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .post-detail {
        margin: 16px auto;
    }

    .title {
        font-size: 20px;
    }

    .content {
        font-size: 15px;
        padding: 16px;
    }

    .card-footer {
        justify-content: space-around;
    }
}

/* 新增评论区样式 */
.comment-section {
    margin-top: 24px;
    border-radius: 12px;
}

.comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.comment-header h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
}

.comment-count {
    color: #909399;
    font-size: 14px;
}

.comment-input {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
}

.input-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.submit-btn {
    align-self: flex-end;
    padding: 8px 24px;
}

.comment-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.comment-item {
    display: flex;
    gap: 16px;
    padding: 16px;
    border-radius: 8px;
    background: #f9fafb;
}

.comment-content {
    flex: 1;
}

.comment-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.comment-username {
    font-weight: 600;
    color: #333;
}

.comment-time {
    font-size: 12px;
    color: #909399;
}

.comment-text {
    margin: 8px 0;
    font-size: 14px;
    line-height: 1.6;
    color: #4a4a4a;
}

.comment-actions {
    display: flex;
    justify-content: flex-end;
    gap: 16px;
    align-items: center;
}

.comment-actions .el-button {
    padding: 4px 8px;
    font-size: 12px;
}

.like-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #909399;
    cursor: pointer;
    transition: all 0.3s ease;
}

.like-btn:hover {
    color: #409EFF;
}

.like-btn.liked {
    color: #409EFF;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .comment-item {
        padding: 12px;
    }

    .comment-input {
        flex-direction: column;
        gap: 12px;
    }

    .comment-avatar {
        align-self: flex-start;
    }
}

/* 添加或修改样式部分 */
.like-btn img,
.view-btn img {
    width: 16px;
    /* 设置图片宽度 */
    height: 16px;
    /* 设置图片高度 */
    vertical-align: middle;
    /* 垂直对齐 */
}

.like-btn,
.view-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    padding: 4px 8px;
    border-radius: 4px;
}

.like-btn:hover,
.view-btn:hover {
    background-color: rgba(64, 158, 255, 0.1);
}

.like-btn.liked img {
    filter: brightness(0) saturate(100%) invert(47%) sepia(82%) saturate(2770%) hue-rotate(199deg) brightness(101%) contrast(107%);
}

.view-btn.viewed img {
    filter: brightness(0) saturate(100%) invert(47%) sepia(82%) saturate(2770%) hue-rotate(199deg) brightness(101%) contrast(107%);
}

/* 响应式设计 */
@media (max-width: 1024px) {
    .rank-image {
        display: none;
    }

    .post-detail {
        margin-left: auto;
        margin-right: auto;
    }
}

.footer {
    margin-top: 100px;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}

/* 新增广告词样式 */
.ad-container {
    position: fixed;
    right: 24px;
    top: 300px;
    width: 200px;
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.ad-block {
    background: #f0f9ff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: transform 0.3s ease;
    border-left: 4px solid #409EFF;
}

.ad-block:hover {
    transform: translateY(-5px);
    background: #ecf5ff;
}

.ad-block h3 {
    color: #2d5af1;
    margin: 0 0 10px 0;
    font-size: 18px;
    font-weight: 600;
}

.ad-block p {
    color: #333;
    margin: 5px 0;
    font-size: 14px;
    line-height: 1.6;
}

/* 响应式设计调整 */
@media (max-width: 1400px) {
    .ad-container {
        display: none;
    }

    .post-detail {
        margin-right: auto;
    }
}

.user-info-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
}

.comment-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

/* 删除按钮样式 */
.user-info-wrapper .el-button {
    padding: 2px 4px;
    font-size: 12px;
}

/* 保留其他删除按钮样式 */
.comment-user .el-button {
    font-size: 12px;
    height: 24px;
    padding: 2px;
    margin-left: 4px;
}

.comment-user .el-button .el-icon {
    font-size: 16px;
}
</style>